var navTabs = [ "mapConfig","mapEngines","wmsConfig","mapToolConfig","owfConfig" ];
var divTabs = [ "geeConfigContainer","map-engines-div","wms-div","map-tools-div","owfConfigContainer" ];


function init() {
	
	if (localStorage.selTab != "" || localStorage.selTab != "undefined") {
		activateTab();
	} else {
		localStorage.selTab = 1;
		activateTab();
	}
	
	emp.$("#proxyActive").click(function() {
		showHide();
	});
	
	toggleInfoSuccess("Initial Load Successful");			
	
	
	emp.$('#mapEngineSelection').change(function() {
		updateSelection(emp.$(this).val());	
	});
	
	emp.$('#mapConfig').click(function() {
		tabSelection( divTabs[0] );	  			
		localStorage.selTab = 0;
	});	  		
	emp.$('#mapEngines').click(function() {
		tabSelection( divTabs[1] );	  			
		localStorage.selTab = 1;
	});
	emp.$('#wmsConfig').click(function() {
		tabSelection( divTabs[2] );		
		localStorage.selTab = 2;
	});	  		
	emp.$('#mapToolConfig').click(function() {
		tabSelection( divTabs[3] );		
		localStorage.selTab = 3;
	});	  	
/*	emp.$('#proxyConfig').click(function() {
		tabSelection( divTabs[4] );		
		localStorage.selTab = 4;
		showHide();
	});  	*/
	emp.$('#owfConfig').click(function() {
		tabSelection( divTabs[4] );		
		localStorage.selTab = 4;
		showHide();
	});

	
	emp.$('#empNavbar ul li a').click(function() {
		removeSelected();
		emp.$( this ).addClass( "selected" );
		emp.$( this ).closest( 'li' ).addClass( 'active' );
		localStorage.selTab = emp.$.inArray(emp.$( this ).attr('id'), navTabs);
	});
	


    emp.$( "#uploadForm" ).on( "change", function() {    	
    	alert('hola');
    	emp.$( this ).submit();
    });
    

	getOwfLibLoc();
	updateProxyConfigGUI();
	showHide();
	
};





function activateTab() {
	tabSelection( divTabs[localStorage.selTab] );
	emp.$( '#' + navTabs[localStorage.selTab] ).closest('li').addClass( 'active' );			
};

function clickErrorHandler() {
	emp.$("#mapConfig").off("click").on("click",  "showHelp()");
	emp.$("#mapEngines").off("click").on("click",  "showHelp()");
	emp.$("#wmsConfig").off("click").on("click",  "showHelp()");
	emp.$("#mapToolConfig").off("click").on("click",  "showHelp()");	  		
	emp.$("#submitAnchor").off("click").on("click",  "showHelp()");
	
	emp.$("#submitAnchor").attr("onclick", "showHelp()");	  		
	emp.$("#mapConfig").attr("onclick", "showHelp()");	  		
	emp.$("#mapEngines").attr("onclick", "showHelp()");
	emp.$("#wmsConfig").attr("onclick", "showHelp()");
	emp.$("#mapToolConfig").attr("onclick", "showHelp()");	  			  		
};

function showHelp() {
	emp.$('#overlay').fadeIn('fast',function() {
        emp.$('#box').animate({'top':'160px'},400);
    });
	
    emp.$('#boxclose').click(function() {
        emp.$('#box').animate({'top':'-400px'},100,function() {
            emp.$('#overlay').fadeOut('fast');
            
            var errorMsgs = ["Missing Property File", "<a onclick='showHelp()'>Details: Click Here</a>"];
            showErrorNotification(errorMsgs);
        });
    });
};  	
   
function removeSelected() {
	emp.$("li").each( function( index ) {
		emp.$( this ).removeClass( "active" );
	});
};		

function updateMapToolsConfig() {
	// get the form values
	var widgetName = emp.$('#widgetName').val();
	var widgetDescr = emp.$('#widgetDescr').val();
	var widgetIconUrl = emp.$('#widgetIcon').val();
	var widgetDisplayName = emp.$('#widgetDisplayName').val();			
	
	emp.$.ajax({
		type: "POST",
		url: '${updateMapTools}',
		data: "widgetName=" + widgetName + "&widgetDescr=" + widgetDescr + "&widgetIconUrl=" + widgetIconUrl + "&widgetDisplayName=" + widgetDisplayName,
		success: function(response) {
			// remove error notification box 
			emp.$('#error-notification').hide('fast');   
			
			if (response.status == "SUCCESS") {					
				updateCpce3dConfigTools();
				toggleInfoSuccess("Settings have been successfully saved");						
				if (emp.$('#error-notification').is(":visible")) {
					emp.$('#error-notification').hide('slow');	
				}					
			} else {
				errorInfo = "<ul>";					
				for (var i = 0; i < response.result.length; i++) {
					errorInfo += "<li>" + "Invalid Field " + "<span>" + response.result[i].field + "</span>: " + response.result[i].code + " : " + response.result[i].defaultMessage + "</li>";
				}
				errorInfo += "</ul>";						
				emp.$('#error-msg').html(errorInfo);
				emp.$('#success-notification').toggle('fast');
				emp.$('#error-notification').show('slow');					
			}					
		},
		error: function(e) {
			alert('Error: ' + e);				
		}								
	});	
}

function showErrorNotification(response) {
	if (response[0] == "SUCCESS") {
		toggleInfoSuccess("Settings have been successfully saved");						
		if (emp.$('#error-notification').is(":visible")) {
			emp.$('#error-notification').hide('slow');	
		}			
	} else {
		var errorInfo = "<ul>";					
		for (var i = 0; i < response.length; i++) {
			errorInfo += "<li>" + "<span>" + response[i] + "</span>" + "</li>";
		}
		errorInfo += "</ul>";									
		emp.$('#error-msg').html(errorInfo);
		emp.$('#success-notification').hide('fast');
		emp.$('#error-notification').show('slow');
	}					
}

function updateMapConfig() {
	// get the form values
	var enterpriseBaseURL = emp.$('#enterpriseBaseURL').val();
	var enterpriseKey = emp.$('#enterpriseKey').val();
	var enableSynapse = emp.$('#enableSynapse').val();
	var enableDebugging = emp.$('#enableDebugging').val();
	var mapEngine = emp.$('#mapEngineSelection').val();
	var lat = emp.$('#defLat').val();
	var lon = emp.$('#defLon').val();
	var scale = emp.$('#defScale').val();

	emp.$.ajax({
		type: "POST",
		url: '${updateGoogleUrl}',
		data: "enterpriseBaseURL=" + enterpriseBaseURL + "&enterpriseKey=" + enterpriseKey + "&enableSynapse=" + enableSynapse + "&enableDebugging=" + enableDebugging + "&mapEngine=" + mapEngine + "&lat=" + lat + "&lon=" + lon + "&scale=" + scale,
		success: function(response) {
			// remove error notification box 
			emp.$('#error-notification').hide('fast');   
			// we have the response
			if (response.status == "SUCCESS") {						
				//updateGoogleMapServerConfigurationGUI();     
				updateCpce3dConfig();
				toggleInfoSuccess("Settings have been successfully saved");
				
				if (emp.$('#error-notification').is(":visible")) {
					emp.$('#error-notification').hide('slow');	
				}
			
			} else {
				errorInfo = "<ul>";					
				for (var i = 0; i < response.result.length; i++) {
					errorInfo += "<li>" + "Invalid Field " + "<span>" + response.result[i].field + "</span>: " + response.result[i].code + " : " + response.result[i].defaultMessage + "</li>";
				}
				errorInfo += "</ul>";						
				emp.$('#error-msg').html(errorInfo);
				emp.$('#success-notification').toggle('fast');
				emp.$('#error-notification').show('slow');					
			}					
		},
		error: function(e) {
			alert('Error: ' + e);				
		}								
	});		
}		

function updateProxyConfig(url) {
	// get the form values 
	var proxyActive  	= emp.$('#proxyActive').is(':checked');
	var proxyHost 		= emp.$('#proxyHost').val();
	var proxyPort		= emp.$('#proxyPort').val();
	var proxyProtocol 	= emp.$('#proxyProtocolSelection').val();

	emp.$.ajax({
		type: "POST",
		url: url,
		data: "proxyHost=" + proxyHost + "&proxyPort=" + proxyPort + "&proxyProtocol=" + proxyProtocol + "&proxyActive=" + proxyActive,
		success: function(response) {
			// remove error notification box 
			emp.$('#error-notification').hide('fast');  
			emp.$('#success-notification').hide('fast');
											
			if (response.status == "OK" || response.status == "200") {														
				//UPDATE GUI FORM HERE 
				updateProxyConfigGui(jQuery.parseJSON(response.result));
				
				toggleInfoSuccess("Settings have been successfully saved");
				
				if (emp.$('#error-notification').is(":visible")) {
					emp.$('#error-notification').hide('slow');	
				}
			
			} else {
				displayError(response.message);
				emp.$('#success-notification').hide('fast');
				updateProxyConfigGui(jQuery.parseJSON(response.result));
			}					
		},
		error: function(e) {
			displayError(arguments);
			updateProxyConfigGui(jQuery.parseJSON(e.responseText));
		}								
	});	
}

function displayError(response) {
	var errorInfo = "<ul>";	
	var i;
	for (i = 0; i < response.length;) {
		errorInfo += "<li>" + "Invalid Field " + "<span>" + response[i].field + "</span>: " + response[i].code + " : " + "process aborted" + "</li>";
		i++;
	} 
	errorInfo += "</ul>";						
	emp.$('#error-msg').html(errorInfo);
	emp.$('#success-notification').toggle('fast');
	emp.$('#error-notification').show('slow');
}

function updateProxyConfigGui(response) {
	emp.$('#proxyActive').prop("checked", response.proxyActive);
	emp.$('#proxyHost').val(response.proxyHost);
	emp.$('#proxyPort').val(response.proxyPort);
}		

function getOwfLibLoc() {
	var controllerURL = "mapengine/config";
	var owfLibLocURL  = controllerURL + "/getOwfLocation";
	
	emp.$.ajax({
		type: "GET",
		url: owfLibLocURL,
		success: function (response) {
			emp.$("#owfLibInput").val(response);
		},
		failure: function (data) {
			alert("FAILURE could NOT update OWF library location");
		}
	});
};

/*function updateOwfLibConfig() {
	// get the form values 
	var owfLibLoc = emp.$('#owfLibLoc').val();

	emp.$.ajax({
		type: "POST",
		url: '${updateOwfLibUrl}',
		data: "owfLibLoc=" + owfLibLoc,
		success: function(response) {
			// remove error notification box 
			emp.$('#error-notification').hide('fast');   
											
			if (arguments[2].statusText == "OK") {
				toggleInfoSuccess("Settings have been successfully saved");						
				
				emp.$('#owfLibLoc').val(response);						
				
				if (emp.$('#error-notification').is(":visible")) {
					emp.$('#error-notification').hide('slow');	
				}					
			} else {
				errorInfo = "<ul>";					
				for (var i = 0; i < response.result.length; i++) {
					errorInfo += "<li>" + "Invalid Field " + "<span>" + response.result[i].field + "</span>: " + response.result[i].code + " : " + response.result[i].defaultMessage + "</li>";
				}
				errorInfo += "</ul>";						
				emp.$('#error-msg').html(errorInfo);
				emp.$('#success-notification').toggle('fast');
				emp.$('#error-notification').show('slow');					
			}					
		},
		error: function(e) {
			alert('Error: ' + e);				
			}								
		});		
	}*/
   
   function toggleInfo(time) {
	   emp.$('#success-notification').fadeOut(time, function() {
		   /*emp.$('#success-msg').html("<span><strong>Success:</strong></span><br/>Current Settings are displayed");
		   emp.$('#success-notification').fadeIn("slow");*/
	   });
   }
   
   function toggleInfoSuccess(infoText) {   
	   infoText = "<strong>Success:</strong><br/>" + infoText;
	   emp.$('#success-notification').fadeIn("slow", function() {				
		   emp.$('#success-msg').html(infoText);
		});
	   toggleInfo(6000);
   }
   
   function toggleError() {
	   emp.$('#success-notification').fadeOut("slow");
	   emp.$('#error-notification').fadeIn('slow');		   
   }
   
   function getPropertyFile(u) {
	   var url = u;
	   window.open(url, "Download");		   
   }
   
   function getPropertiesInfo() {
	   emp.$('#propertiesInfo').dialog({
		   model: true,
		   buttons: {
			   Ok: function() {
				   emp.$(this).dialog("close");
			   }
		   }
	   });
   }
   
   function tabSelection(active) {		   
	   hideAllContent();
	   showActiveContent(active);
   }
   
   function hideAllContent() {		   
	   for (var i = 0; i < divTabs.length; i++) {
		   emp.$('#'+divTabs[i]).fadeOut("fast");
	   }
   }
   
   function showActiveContent(active) {
	   emp.$('#' + active).fadeIn("slow");
	   emp.$('#' + active).addClass("active");		
   }
   
   function showHide() {
	   trueFalse = emp.$('#proxyActive').is(':checked');
	   if (trueFalse) {
		   emp.$('#proxySettings').find('input[type=text],input[type=number], textarea, select, a').removeAttr('disabled');			   
	   } else {			   
		   emp.$('#proxySettings').find('input[type=text],input[type=number], textarea, select, a').attr('disabled','disabled');			   
	   }		   
   };
   
   function serverReload() {
	   location.reload(true);
   };
   
   function updateOwfLibLoc() {
		var controllerURL = "mapengine/config";
		var owfLibLocURL  = controllerURL + "/update/owfLibLocation";
		var owfLibloc = emp.$("#owfLibInput").val();
		
		emp.$.ajax({
			type: "POST",
			url: owfLibLocURL,
			data: "libLocation=" + owfLibloc,
			success: function (response) {
				emp.$("#owfLibInput").val(response);
				$('#msgbox').text('Entry has been edited successfully');          		
					$('#msgbox').dialog( {
						title: 'Success',
						modal: true,
						buttons: {
							"Ok": function() {
								$(this).dialog("close");     									      									
							}
						}					      						
					});
			},
			failure: function (data) {
				alert("FAILURE could NOT update OWF library location");
			}
		});
	};
	
   function isVerified() {
  		emp.$('#success-notification').remove();
  		clickErrorHandler();
  		showHelp();
 	};	 	
 	
	